package com.lee

import com.sun.org.apache.xerces.internal.parsers.XMLDocumentParser
import com.sun.xml.internal.messaging.saaj.util.XMLDeclarationParser
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
import org.grails.datastore.mapping.query.Query

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = true)
class UserController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond User.list(params), model:[userCount: User.count()]
    }

    def show(User user) {
        respond user
    }

    def create() {
        respond new User(params)
    }

    @Transactional
    def save(User user) {
        if (user == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond user.errors, view:'create'
            return
        }

        user.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect user
            }
            '*' { respond user, [status: CREATED] }
        }
    }

    def edit(User user) {
        respond user
    }

    @Transactional
    def update(User user) {
        if (user == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond user.errors, view:'edit'
            return
        }

        user.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect user
            }
            '*'{ respond user, [status: OK] }
        }
    }

    @Transactional
    def delete(User user) {

        if (user == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        user.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    /**
     *  创建简单的xml
     */
    def createXml() {
        def sw = new StringWriter()
        MarkupBuilder mk = new MarkupBuilder(sw)
        mk.users {
            user {
                name("张三")
                age(20)
                sex("男")
                addr("山东")
            }
            user {
                name("小丽")
                age(18)
                sex("女")
                addr("北京")
            }
            user {
                name("小王")
                age(22)
                sex("男")
                addr("贵州")
            }
        }
        def file = new File("d:\\usr.xml")
        def pw = new PrintWriter(file)
        pw.print(sw)
        pw.flush()
        pw.close()
        println sw
        render "简单的xml"

    }

    /**
     * 创建复杂的xml
     * @return
     */
    def complexXml() {
        def builder=new groovy.xml.StreamingMarkupBuilder()
        builder.encoding='utf-8' //设置编码
        def person = {
            mkp.xmlDeclaration() //<?xml version='1.0'?>
            mkp.declareNamespace("info":"userInfo") //添加命名空间
            mkp.declareNamespace("location":"http://www.baidu.com")
            persons {
                comment << "用户信息"  //添加注释
                info.person(id:3){
                    name("张三")
                    age(22)
                    sex("男")
                    location.addr('重庆')
                }
                info.person(id:1){
                    name("李四")
                    age(20)
                    sex("男")
                    location.addr('北京')
                }
                info.person(id:2){
                    name("小丽")
                    age(19)
                    sex("女")
                    location.addr('天津')
                }
            }

        }
        def writer = new StringWriter()
        writer << builder.bind(person)
        def file = new File("d:\\user.xml")
        def pw = new PrintWriter(file)
        pw.print(writer)
        pw.flush()
        pw.close()
        println writer
        render "复杂"
    }

    /**
     *  解析xml
     */
    @Transactional
    def readXml() {
        params.remove("controller")
        params.remove("format")
        params.remove("action")
        def xml = new XmlSlurper()
        def result = xml.parse(new File("d:\\usr.xml"))
        result.user.each {k->
            params.name = k.name.toString()
            params.age  = k.age
            params.sex  = k.sex.toString()
            params.addr = k.addr.toString()
            User user = new User(params)
            user.save(flush:true)
            //打印错误
            //println user.errors
        }
        render "解析成功"
    }

    /**
     *  解析带有命名空间的xml
     */
    def readComplexXml() {
        def xml = new XmlSlurper()
        def result = xml.parse(new File("d:\\user.xml"))
        println result
        render "解析完成"
    }
}
